package com.example.sunmi_status_light_manager

import android.content.Context
import android.util.Log
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import com.sunmi.peripheralsdk.StatusLightManager
import com.sunmi.peripheralsdk.Color

/** SunmiStatusLightManagerPlugin */
class SunmiStatusLightManagerPlugin: FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel
  private lateinit var context: Context

  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "sunmi_status_light_manager")
    channel.setMethodCallHandler(this)
    context = flutterPluginBinding.applicationContext
  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    when (call.method) {
      "initialize" -> {
        Log.d("SunmiStatusLightManagerPlugin", "event:initialize")
        initializeStatusLight(result)
      }
      "setColor" -> {
        Log.d("SunmiStatusLightManagerPlugin", "event:setColor")
        val colorName = call.argument<String>("color")
        setColor(colorName, result)
      }
      "turnOff" -> {
        Log.d("SunmiStatusLightManagerPlugin", "event:turnOff")
        turnOff(result)
      }
      "setFlashing" -> {
        Log.d("SunmiStatusLightManagerPlugin", "event:setFlashing")
        val colorName = call.argument<String>("color")
        val onMs = call.argument<Int>("onMs") ?: 500
        val offMs = call.argument<Int>("offMs") ?: 500
        setFlashing(colorName, onMs, offMs, result)
      }
      "setMultiFlashing" -> {
        Log.d("SunmiStatusLightManagerPlugin", "event:setMultiFlashing")
        val colorNames = call.argument<List<String>>("colors") ?: emptyList()
        val onMs = call.argument<List<Int>>("onMs") ?: emptyList()
        val offMs = call.argument<List<Int>>("offMs") ?: emptyList()
        setMultiFlashing(colorNames, onMs, offMs, result)
      }
      "destroy" -> {
        Log.d("SunmiStatusLightManagerPlugin", "event:destroy")
        destroy(result)
      }
      else -> {
        result.notImplemented()
      }
    }
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  private fun initializeStatusLight(result: Result) {
    try {
      StatusLightManager.init(context) { success ->
        Log.d("SunmiStatusLightManagerPlugin.initializeStatusLight", "success: $success")
        if (success) {
          StatusLightManager.openDevice()
          result.success(true)
        } else {
          result.success(false)
        }
      }
    } catch (e: Exception) {
      Log.e("SunmiStatusLightManagerPlugin.initializeStatusLight", "error: ${e.message}")
      result.success(false)
    }
  }

  private fun setColor(colorName: String?, result: Result) {
    try {
      val color = getSunmiColor(colorName)
      if (color != null) {
        StatusLightManager.setColor(color)
        result.success(true)
      } else {
        result.success(false)
      }
    } catch (e: Exception) {
      result.success(false)
    }
  }

  private fun turnOff(result: Result) {
    try {
      StatusLightManager.turnOff()
      result.success(true)
    } catch (e: Exception) {
      result.success(false)
    }
  }

  private fun setFlashing(colorName: String?, onMs: Int, offMs: Int, result: Result) {
    try {
      val color = getSunmiColor(colorName)
      if (color != null) {
        StatusLightManager.setFlashing(color, onMs, offMs)
        result.success(true)
      } else {
        result.success(false)
      }
    } catch (e: Exception) {
      result.success(false)
    }
  }

  private fun setMultiFlashing(colorNames: List<String>, onMs: List<Int>, offMs: List<Int>, result: Result) {
    try {
      if (colorNames.isEmpty() || onMs.isEmpty() || offMs.isEmpty()) {
        result.success(false)
        return
      }

      val colors = colorNames.mapNotNull { getSunmiColor(it) }.toTypedArray()
      val onMsArray = onMs.toIntArray()
      val offMsArray = offMs.toIntArray()

      if (colors.size == colorNames.size) {
        StatusLightManager.setMultiFlashing(colors, onMsArray, offMsArray)
        result.success(true)
      } else {
        result.success(false)
      }
    } catch (e: Exception) {
      result.success(false)
    }
  }

  private fun destroy(result: Result) {
    try {
      StatusLightManager.destroy(context)
      result.success(true)
    } catch (e: Exception) {
      result.success(false)
    }
  }

  private fun getSunmiColor(colorName: String?): Color? {
    return when (colorName) {
      "red" -> Color.Red
      "green" -> Color.Green
      "blue" -> Color.Blue
      "yellow" -> Color.Yellow
      "magenta" -> Color.Magenta
      "cyan" -> Color.Cyan
      "white" -> Color.White
      else -> null
    }
  }
}
